<script setup lang="ts">
import { uploadFile } from '@/api/consult'
import { VisitTypeEnum } from '@/enums'
import router from '@/router'
import { useConsultStore } from '@/stores'
import type { illnessType, Image } from '@/types/consult'
import { showConfirmDialog } from 'vant'
import type {
  UploaderAfterRead,
  UploaderFileListItem
} from 'vant/lib/uploader/types'
import { computed, onMounted } from 'vue'
import { ref } from 'vue'
import { useRoute } from 'vue-router'
import { useRouter } from 'vue-router'
import { IllnessTimeOpts, VisitOpts } from '@/constants/consult'

const form = ref<illnessType>({
  illnessTime: '',
  consultFlag: 0,
  illnessDesc: '',
  pictures: []
})

// 上传图片
// 1. 用户选择图片，file控件读取图片内容
const fileList = ref<UploaderFileListItem[]>([]) // 上传图片绑定
// 2.执行onAfterRead函数
// 文件读取完成后的回调函数
const onAfterRead: UploaderAfterRead = async (items) => {
  if (Array.isArray(items)) return // 判断是否是数组（多个图片上传），是的话阻止
  if (!items.file) return // 图片不存在阻止
  items.status = 'uploading'
  items.message = '上传中...'
  // 3.调接口做图片上传
  const formData = new FormData()
  formData.append('file', items.file)
  try {
    const { data } = await uploadFile(formData)
    console.log(data)
    items.status = 'done'
    items.message = ''
    form.value.pictures.push(data)
  } catch (error) {
    items.status = 'failed'
    items.message = '上传失败'
  }
}

// 删除文件的回调函数
const onDeleteImg = (items: UploaderFileListItem, data: { index: number }) => {
  form.value.pictures.splice(data.index, 1)
}

// 提交
const disabled = computed(() => {
  return (
    !form.value.illnessDesc ||
    !form.value.illnessTime ||
    (!form.value.consultFlag && form.value.consultFlag !== 0)
  )
})

const consultStore = useConsultStore()
// const router = useRouter()
const route = useRoute()

const next = () => {
  consultStore.setIllness(form.value)
  router.push('/user/patient?isChange=1')
}

// 用户到达这个页面，如果以前有填写过的数据，提醒用户是否使用以前的数据，如果使用则把数据回填 否则。。。
onMounted(async () => {
  if (consultStore.consult.illnessDesc) {
    await showConfirmDialog({
      closeOnClickOverlay: false, // 页面关闭时弹层不消失
      title: '友情提示',
      message: '您是否要使用之前填写的数据？'
    })

    form.value.consultFlag = consultStore.consult.consultFlag as VisitTypeEnum
    form.value.illnessDesc = consultStore.consult.illnessDesc
    form.value.illnessTime = consultStore.consult.illnessTime
    form.value.pictures = consultStore.consult.pictures as Image[]

    fileList.value = consultStore.consult.pictures as UploaderFileListItem[]
  }
})
</script>

<template>
  <div class="consult-illness-page">
    <van-nav-bar
      fixed
      title="图文问诊"
      left-arrow
      @click-left="$router.back()"
    />
    <!-- 医生提示 -->
    <div class="illness-tip van-hairline--bottom">
      <img class="img" src="@/assets/avatar-doctor.svg" />
      <div class="info">
        <p class="tit">在线医生</p>
        <p class="tip">
          请描述你的疾病或症状、是否用药、就诊经历，需要我听过什么样的帮助
        </p>
        <p class="safe">
          <cp-icon name="consult-safe" /><span>内容仅医生可见</span>
        </p>
      </div>
    </div>
    <!-- 收集信息 -->
    <div class="illness-form">
      <van-field
        type="textarea"
        rows="3"
        placeholder="请详细描述您的病情，病情描述不能为空"
        v-model="form.illnessDesc"
      ></van-field>
      <div class="item">
        <p>本次患病多久了？</p>
        <cp-radio-btn
          :options="IllnessTimeOpts"
          v-model="form.illnessTime"
        ></cp-radio-btn>
      </div>
      <div class="item">
        <p>此次病情是否去医院就诊过？</p>
        <cp-radio-btn
          :options="VisitOpts"
          v-model="form.consultFlag"
        ></cp-radio-btn>
      </div>
      <div class="illness-img">
        <!-- upload-icon  上传区域图标名称或图片链接,等同于 Icon 组件的 name 属性 
            upload-text	上传区域文字提示
            max-size	文件大小限制，单位为 byte
            max-count	文件上传数量限制
            @delete	删除文件预览时触发
            after-read	文件读取完成后的回调函数
          -->
        <van-uploader
          upload-icon="phono-o"
          upload-text="上传图片"
          :max-size="5 * 1024 * 1024"
          max-count="9"
          :after-read="onAfterRead"
          @delete="onDeleteImg"
          v-model="fileList"
        ></van-uploader>
        <p class="tip">上传内容仅医生可见,最多9张图,最大5MB</p>
      </div>
      <van-button
        :class="{ disabled }"
        @click="next"
        type="primary"
        block
        round
      >
        下一步
      </van-button>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.van-button {
  font-size: 16px;
  margin-bottom: 30px;
  &.disabled {
    opacity: 1;
    background: #fafafa;
    color: #d9dbde;
    border: #fafafa;
  }
}
.illness-img {
  padding-top: 16px;
  margin-bottom: 40px;
  display: flex;
  align-items: center;
  .tip {
    font-size: 12px;
    color: var(--cp-tip);
  }
  ::v-deep() {
    .van-uploader {
      &__preview {
        &-delete {
          left: -6px;
          top: -6px;
          border-radius: 50%;
          background-color: var(--cp-primary);
          width: 20px;
          height: 20px;
          &-icon {
            transform: scale(0.9) translate(-22%, 22%);
          }
        }
        &-image {
          border-radius: 8px;
          overflow: hidden;
        }
      }
      &__upload {
        border-radius: 8px;
      }
      &__upload-icon {
        color: var(--cp-text3);
      }
    }
  }
}
.consult-illness-page {
  padding-top: 46px;
}
.illness-tip {
  display: flex;
  padding: 15px;
  .img {
    width: 52px;
    height: 52px;
    border-radius: 4px;
    overflow: hidden;
    margin-top: 10px;
  }
  .info {
    flex: 1;
    padding-left: 12px;
    .tit {
      font-size: 16px;
      margin-bottom: 5px;
    }
    .tip {
      padding: 12px;
      background: var(--cp-bg);
      color: var(--cp-text3);
      font-size: 13px;
      margin-bottom: 10px;
    }
    .safe {
      font-size: 10px;
      color: var(--cp-text3);
      display: flex;
      align-items: center;
      .cp-icon {
        font-size: 12px;
        margin-right: 2px;
      }
    }
  }
}
.illness-form {
  padding: 15px;
  .van-field {
    padding: 0;
    &::after {
      border-bottom: none;
    }
  }
  .item {
    > p {
      color: var(--cp-text3);
      padding: 15px 0;
    }
  }
}
</style>
